package org.joy.db2;

import java.util.LinkedList;
import java.util.List;

import com.sleepycat.bind.tuple.IntegerBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.db.DatabaseEntry;

public class DocumentEntry extends Entry {
    private int hash;
    private String URL;
    private List<String> paragraphs;

    public DocumentEntry() {
    }

    public DocumentEntry(int hash, String uRL, List<String> paragraphs) {
	super();
	this.hash = hash;
	URL = uRL;
	this.paragraphs = paragraphs;
    }

    public int getHash() {
	return hash;
    }

    public void setHash(int hash) {
	this.hash = hash;
    }

    public String getURL() {
	return URL;
    }

    public void setURL(String uRL) {
	URL = uRL;
    }

    public List<String> getParagraphs() {
	return paragraphs;
    }

    public void setParagraphs(List<String> paragraphs) {
	this.paragraphs = paragraphs;
    }

    public String getDocument() {
	StringBuffer sb = new StringBuffer();
	for (String s : paragraphs) {
	    sb.append(s);
	}
	return sb.toString();
    }

    @Override
    public DatabaseEntry getKeyEntry() {
	DatabaseEntry keyE = new DatabaseEntry();
	IntegerBinding.intToEntry(hash, keyE);
	return keyE;
    }

    @Override
    public DatabaseEntry getValEntry() {
	TupleOutput out = new TupleOutput();
	out.writeString(URL);
	out.writeInt(paragraphs.size());
	for (String p : paragraphs) {
	    out.writeString(p);
	}
	return new DatabaseEntry(out.getBufferBytes());
    }

    @Override
    public void read(DatabaseEntry key, DatabaseEntry val) {
	this.hash = IntegerBinding.entryToInt(key);
	TupleInput in = new TupleInput(val.getData());
	this.URL = in.readString();
	this.paragraphs = new LinkedList<String>();
	int length = in.readInt();
	for (int i = 0; i < length; i++) {
	    paragraphs.add(in.readString());
	}
    }

}
